package com.xncoding.trans.controller;

import com.xncoding.trans.entity.Menu;
import com.xncoding.trans.pojo.MenuNode;
import com.xncoding.trans.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class AdminCrontroller {

	
	@Autowired
	MenuService menuService;
	
	@RequestMapping("/addmenu.json") 
	public @ResponseBody String add() throws Exception{
		menuService.addMenu(null);
		//模拟改变缓存
		return "{\"success\":true}";
	}
	
	@RequestMapping("/getmenu.json") 
	public @ResponseBody Menu getMenu(String menuId) throws Exception{
		return menuService.getMenu(menuId);
	}
	
	@RequestMapping("/tree.json") 
	public @ResponseBody MenuNode tree() throws Exception{
		return menuService.getMenuTree();
	}

	@PostMapping("/treeObjTest")
	public @ResponseBody List<Menu> treeObjTest(@RequestBody Menu m) throws Exception{
		return menuService.treeObjTest(m);
	}

	@RequestMapping("/treeObjTest00")
//	@CacheEvict(value = "treeObjTestAll",keyGenerator = "mycleanKeyGenerator",allEntries = true)
//	@CacheEvict(value = "treeObjTestAll",cacheManager = "cacheClearManager",key = "#m.id",allEntries = false)
	@CacheEvict(value = "treeObjTestAll",cacheManager = "cacheClearManager", key = "#m.id", allEntries = false)
	public String treeObjTest00(@RequestBody Menu m) throws Exception{
		System.out.println("0000000000000");
		return "22";
	}

	@RequestMapping("/treeObjTest01")
	public @ResponseBody List<Menu> treeObjTest01(@RequestBody Menu m) throws Exception{
		return menuService.treeObjTest01(m);
	}
	@RequestMapping("/treeObjTest03")
	@Cacheable(value = "trl03",unless = "#result == null or #m.code eq 'menu' ")
	public @ResponseBody List<Menu> treeObjTest03(@RequestBody Menu m) throws Exception{

		Menu root = new Menu();
		root.setCode("root");
		root.setName("系统管理");
		root.setParentId(null);

		Menu menu = new Menu();
		menu.setCode("menu");
		menu.setName("菜单管理");

		List<Menu> list = new ArrayList<>();
		list.add(root);
		list.add(menu);

		return list;
	}

	/**
	 * 当返回结果是22时候清楚缓存
	 * @param str
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/treeObjTest02/{str}")
	@CacheEvict(value = "trl03",condition = "#result eq '22' ",allEntries = true)
	public String treeObjTest02(@PathVariable String str) throws Exception{
		if ("1".equals(str)){
			return "11";
		}
		return "22";
	}


	/**
	 * 当返回结果是22时候清楚缓存
	 * @param str
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/treeObjTest05/{str}")
	@Cacheable(value = "trl05",unless = "#result.contains('22') ")
	public String treeObjTest05(@PathVariable String str) throws Exception{
		return str;
	}
	
	
	
	
	
}
